import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:tihai/entity/problem.dart';
import 'package:tihai/entity/type.dart';
import 'package:tihai/util/network.dart';
import 'package:tihai/util/storage.dart';

import '../../entity/result.dart';
import '../home/home_page.dart';

class TypeHomePage extends StatefulWidget {
  const TypeHomePage({Key? key}) : super(key: key);

  @override
  State<TypeHomePage> createState() => _TypeHomePageState();
}

class _TypeHomePageState extends State<TypeHomePage> {

  dynamic dataList = [];
  dynamic type;
  dynamic loginId;

  @override
  void initState() {
    super.initState();
    load();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    load();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: type==null ? const Text("") : Text(type.name),
      ),
      body: initTypeList(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushNamed(context, "/problem", arguments: type.id);
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  load() async {
    await loadData();
    await initTypeList();

  }

  loadData() async {
    TypeBean typeBean = ModalRoute.of(context)!.settings.arguments as TypeBean;
    var answerId = await Storage.getString("userId");
    Map<String, dynamic> data = {};
    data["typeId"] = typeBean.id;
    var listResult = await getListAPI(ProblemBean(), API.selectProblemList, data);
    setState(() {
      dataList = listResult;
      type = typeBean;
      loginId = answerId;
    });
  }

  initTypeList() {
    return ListView.builder(
        itemCount: dataList.isEmpty ? 0 : dataList.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {},
            child: Card(
              margin: const EdgeInsets.all(10.0),
              child: Column(
                children: [
                  Text(
                    "题目：${dataList[index].title}",
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis, // 显示不完，就在后面显示点点
                    style: const TextStyle(
                      fontSize: 18.0, // 文字大小
                      color: Colors.blueAccent, // 文字颜色
                    ),
                  ),
                  Text(
                    "奖励：${dataList[index].score}金币", maxLines: 3,
                    overflow: TextOverflow.ellipsis, // 显示不完，就在后面显示点点
                    style: const TextStyle(
                      fontSize: 18.0, // 文字大小
                      color: Colors.orangeAccent, // 文字颜色
                    ),
                  ),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "A");
                      },
                      child: Text("选项A：${dataList[index].choiceA}")),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "B");
                      },
                      child: Text("选项B：${dataList[index].choiceB}")),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "C");
                      },
                      child: Text("选项C：${dataList[index].choiceC}")),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "D");
                      },
                      child: Text("选项D：${dataList[index].choiceD}")),
                ],
              ),
            ),
          );
        });
  }

  void checkAnswer(int index, String choice) async {
    if (choice == dataList[index].answer) {
      Fluttertoast.showToast(
          msg: "回答正确,奖励${dataList[index].score}金币",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.blueAccent,
          textColor: Colors.white,
          fontSize: 16.0);
      Map<String, dynamic> data = {};
      data["problemId"] = "${dataList[index].id}";
      data["score"] = "${dataList[index].score}";
      data["askId"] = "$loginId";
      Result result = await postAPI(API.deleteProblemById, data);
    } else {
      Fluttertoast.showToast(
          msg: "回答错误,扣除${(dataList[index].score/2).round()}金币",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.redAccent,
          textColor: Colors.white,
          fontSize: 16.0);
      Map<String, dynamic> data = {};
      data["problemId"] = "${dataList[index].id}";
      data["score"] = "${-(dataList[index].score/2).round()}";
      data["askId"] = "$loginId";
      Result result = await postAPI(API.deleteProblemById, data);
    }
  }
}
